根據Day14的新的架構,我修改我的/app/graphql/query/query_type.rb這支檔案
app/graphql/type/query_type.rb
module Types
  class QueryType < BaseObject
    field :all_posts, [PostType], null: false
    field :find_post, PostType, null: false do
      description 'Find an post by ID'
      argument :id, ID, required: true
    end
    field :find_posts_by_type, [PostType], null: false do
      description 'Find an post by type'
      argument :id, ID, required: true
    end
    def all_posts
      posts = Post.all
      result = posts.map {|c| {id: c.id, title: c.title, content: c.content, type: c.type.name}}
      return result
    end
    def find_post(id: id)
      post = Post.find(id)
      return {id: post.id, title: post.title, postontent: post.content, type: post.type.name}
    end
    def find_posts_by_type(id: id)
      posts = Post.where("type_id = ?", id)
      result = posts.map {|c| {id: c.id, title: c.title, content: c.content, type: c.type.name}}
      return result
    end
  end
end
光是修改這個不夠,因為我們回傳的資料是PostTypetType,但現在app/graphql/type/post_type.rb還沒有新增type這個field,所以需要修改這支檔案:app/graphql/type/post_type.rb
module Types
  class PostType < BaseObject
    field :id, ID, null: false
    field :title, String, null: false
    field :content, String, null: false
    field :type, String, null: false
  end
end
all_posts方法,基本沒做甚麼大修改,但我們希望抓出來的資料可以顯示他的分類名稱,因此使用map方法,把他的value重新放到一個hash上面。
find_post則接收一個id,找出相對應的文章。
而find_posts_by_type接收一個id,找出相對於該id的分類的文章們,結果如下: